/* RgrClient.java
 * Brent Woodhouse
 * This file contains the code for the Ringer client for VOIP app.  
 */

package project6.voip;
import java.net.*;
import java.io.*;

public class RgrClient
{
	Socket socket = null;
	BufferedReader in = null;
	PrintWriter out = null;
	int port = 0;
	String user;
	
	public RgrClient(String user, int port)
	{
		this.user = user;
		this.port = port;
	}

	// use destPort 65534 to connect with rgrServer
	public void initCall(String rgrServerIp, int destPort){
		try {
			System.out.println("Creating socket...");
			// Try to go through router eventually?
			InetAddress serverAddr = InetAddress.getByName(rgrServerIp);
			socket = new Socket(serverAddr, destPort);
			System.out.println("Socket created!");
			
			System.out.println("Creating reader...");
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			System.out.println("Reader created!");
			
			System.out.println("Creating writer...");
			out = new PrintWriter(socket.getOutputStream(), true);
			System.out.println("Writer created!");
			
			// Send calling message
			out.println("Calling");
			out.println(user);
			
			// Have GUI play ringtone
		
			// Wait for "begin" or "end"
			// if begin, start Voice Capture Client?
			// if end, run endCall
		}
		catch(IOException e)
		{
			System.err.println(e.getMessage());
			System.exit(1);
		}
	}
	
	public void endCall(){
		out.println("End call");
		
		// End Voice Capture Client
		
		// close sockets
		closeAll();
	}
	
	public void closeAll()//Closes all connections to the RgrServer that this instance of RgrClient has.
	{
		try
		{
			System.out.println("Closing...");
			socket.close();
			in.close();
			System.out.println("Closed!");
		}
		catch(IOException e)
		{
			System.err.println("Could not close everything");
		}
	}
}
